from rest_framework import serializers

from Group.models import TeamDetail, Team
from Group.serializers import TeamCreatorSerializer


class TeamBaseSerializer(serializers.ModelSerializer):
    creator = TeamCreatorSerializer(read_only=True)
    memberCount = serializers.SerializerMethodField(read_only=True)
    createTime = serializers.DateTimeField(source='create_time', format='%Y-%m-%d', read_only=True)
    teamType = serializers.IntegerField(source='team_type', read_only=True)

    class Meta:
        model = Team
        fields = ('id', 'name', 'creator', 'memberCount' , 'teamType',
                  'createTime',)

    def get_memberCount(self, instance):
        return instance.total_members


class TeamHeaderInfoSerializer(serializers.ModelSerializer):
    memberCount = serializers.SerializerMethodField(read_only=True)
    createTime = serializers.DateTimeField(source='create_time', format='%Y-%m-%d', read_only=True)
    background = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Team
        fields = ('id', 'name', 'memberCount',
                  'createTime', 'background',)

    def get_memberCount(self, instance):
        return instance.total_members

    def get_background(self, instance):
        # 判断 avatar 是否为空
        if instance.team_detail.avatar:
            return instance.team_detail.avatar.url
        return None


class TeamDetailSerializer(serializers.ModelSerializer):
    background = serializers.CharField(source='avatar', read_only=True)
    baseInfo = serializers.SerializerMethodField(read_only=True)

    class Meta:
        fields = ('id', 'baseInfo', 'background', 'announcement')
        model = TeamDetail

    def get_baseInfo(self, instance):
        return TeamBaseSerializer(instance.team).data


class UpdateTeamAnnouncementViewSerializer(serializers.ModelSerializer):
    class Meta:
        model = TeamDetail
        fields = ('announcement',)
